package com.css.zfzx.sjcj.modules.hddcwyGeochemicalSvyPoint.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.analysis.vo.HddcAppZztCountVo;
import com.css.zfzx.sjcj.modules.hddcGeochemicalSvyPoint.repository.HddcGeochemicalsvypointRepository;
import com.css.zfzx.sjcj.modules.hddcGeochemicalSvyPoint.repository.entity.HddcGeochemicalsvypointEntity;
import com.css.zfzx.sjcj.modules.hddcGeochemicalSvyPoint.viewobjects.HddcGeochemicalsvypointVO;
import com.css.zfzx.sjcj.modules.hddcwyFaultSvyPoint.repository.entity.HddcWyFaultsvypointEntity;
import com.css.zfzx.sjcj.modules.hddcwyGeochemicalSvyPoint.repository.HddcWyGeochemicalsvypointNativeRepository;
import com.css.zfzx.sjcj.modules.hddcwyGeochemicalSvyPoint.repository.HddcWyGeochemicalsvypointRepository;
import com.css.zfzx.sjcj.modules.hddcwyGeochemicalSvyPoint.repository.entity.HddcWyGeochemicalsvypointEntity;
import com.css.zfzx.sjcj.modules.hddcwyGeochemicalSvyPoint.service.HddcWyGeochemicalsvypointService;
import com.css.zfzx.sjcj.modules.hddcwyGeochemicalSvyPoint.viewobjects.HddcWyGeochemicalsvypointQueryParams;
import com.css.zfzx.sjcj.modules.hddcwyGeochemicalSvyPoint.viewobjects.HddcWyGeochemicalsvypointVO;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author zhangcong
 * @date 2020-12-02
 */
@Service
public class HddcWyGeochemicalsvypointServiceImpl implements HddcWyGeochemicalsvypointService {

	@Autowired
    private HddcWyGeochemicalsvypointRepository hddcWyGeochemicalsvypointRepository;
    @Autowired
    private HddcWyGeochemicalsvypointNativeRepository hddcWyGeochemicalsvypointNativeRepository;
    @Autowired
    private HddcGeochemicalsvypointRepository hddcGeochemicalsvypointRepository;
    @Override
    public JSONObject queryHddcWyGeochemicalsvypoints(HddcWyGeochemicalsvypointQueryParams queryParams,int curPage,int pageSize) {
        Page<HddcWyGeochemicalsvypointEntity> hddcWyGeochemicalsvypointPage = this.hddcWyGeochemicalsvypointNativeRepository.queryHddcWyGeochemicalsvypoints(queryParams,curPage,pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcWyGeochemicalsvypointPage);
        return jsonObject;
    }


    @Override
    public HddcWyGeochemicalsvypointEntity getHddcWyGeochemicalsvypoint(String uuid) {
        HddcWyGeochemicalsvypointEntity hddcWyGeochemicalsvypoint = this.hddcWyGeochemicalsvypointRepository.findById(uuid).orElse(null);
         return hddcWyGeochemicalsvypoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcWyGeochemicalsvypointEntity saveHddcWyGeochemicalsvypoint(HddcWyGeochemicalsvypointEntity hddcWyGeochemicalsvypoint) {
        String uuid = UUIDGenerator.getUUID();
        hddcWyGeochemicalsvypoint.setUuid(uuid);
        if(StringUtils.isEmpty(hddcWyGeochemicalsvypoint.getCreateUser())){
            hddcWyGeochemicalsvypoint.setCreateUser(PlatformSessionUtils.getUserId());
        }
        hddcWyGeochemicalsvypoint.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcWyGeochemicalsvypoint.setIsValid("1");

        HddcGeochemicalsvypointEntity hddcGeochemicalsvypointEntity=new HddcGeochemicalsvypointEntity();
        BeanUtils.copyProperties(hddcWyGeochemicalsvypoint,hddcGeochemicalsvypointEntity);
        hddcGeochemicalsvypointEntity.setExtends4(hddcWyGeochemicalsvypoint.getTown());
        hddcGeochemicalsvypointEntity.setExtends5(String.valueOf(hddcWyGeochemicalsvypoint.getLon()));
        hddcGeochemicalsvypointEntity.setExtends6(String.valueOf(hddcWyGeochemicalsvypoint.getLat()));
        this.hddcGeochemicalsvypointRepository.save(hddcGeochemicalsvypointEntity);

        this.hddcWyGeochemicalsvypointRepository.save(hddcWyGeochemicalsvypoint);
        return hddcWyGeochemicalsvypoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcWyGeochemicalsvypointEntity updateHddcWyGeochemicalsvypoint(HddcWyGeochemicalsvypointEntity hddcWyGeochemicalsvypoint) {
        HddcWyGeochemicalsvypointEntity entity = hddcWyGeochemicalsvypointRepository.findById(hddcWyGeochemicalsvypoint.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcWyGeochemicalsvypoint);
        hddcWyGeochemicalsvypoint.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcWyGeochemicalsvypoint.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcWyGeochemicalsvypointRepository.save(hddcWyGeochemicalsvypoint);
        return hddcWyGeochemicalsvypoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcWyGeochemicalsvypoints(List<String> ids) {
        List<HddcWyGeochemicalsvypointEntity> hddcWyGeochemicalsvypointList = this.hddcWyGeochemicalsvypointRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcWyGeochemicalsvypointList) && hddcWyGeochemicalsvypointList.size() > 0) {
            for(HddcWyGeochemicalsvypointEntity hddcWyGeochemicalsvypoint : hddcWyGeochemicalsvypointList) {
                this.hddcWyGeochemicalsvypointRepository.delete(hddcWyGeochemicalsvypoint);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public BigInteger queryHddcWyGeochemicalsvypoint(HddcAppZztCountVo queryParams) {
        BigInteger bigInteger = hddcWyGeochemicalsvypointNativeRepository.queryHddcWyGeochemicalsvypoint(queryParams);
        return bigInteger;
    }

    @Override
    public List<HddcWyGeochemicalsvypointEntity> findAllByCreateUserAndTaskIdAndProjectIdAndIsValid(String userId, String taskId, String projectId, String isValid) {
        List<HddcWyGeochemicalsvypointEntity> list = hddcWyGeochemicalsvypointRepository.findAllByCreateUserAndTaskIdAndProjectIdAndIsValid(userId, taskId, projectId, isValid);
        return list;
    }

    @Override
    public void exportFile(HddcAppZztCountVo queryParams, HttpServletResponse response) {
        List<HddcWyGeochemicalsvypointEntity> hddcWyGeochemicalsvypointEntity = hddcWyGeochemicalsvypointNativeRepository.exportChemPoint(queryParams);
        List<HddcWyGeochemicalsvypointVO> list=new ArrayList<>();
        for (HddcWyGeochemicalsvypointEntity entity:hddcWyGeochemicalsvypointEntity) {
            HddcWyGeochemicalsvypointVO hddcWyGeochemicalsvypointVO=new HddcWyGeochemicalsvypointVO();
            BeanUtils.copyProperties(entity,hddcWyGeochemicalsvypointVO);
            list.add(hddcWyGeochemicalsvypointVO);
        }
        EasyPoiExcelUtil.exportExcel(list,"地球化学探测测点-点","地球化学探测测点-点", HddcWyGeochemicalsvypointVO.class,"地球化学探测测点-点.xls",response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcWyGeochemicalsvypointVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcWyGeochemicalsvypointVO.class, params);
            List<HddcWyGeochemicalsvypointVO> list = result.getList();
            // Excel条数据
            int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcWyGeochemicalsvypointVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcWyGeochemicalsvypointVO hddcWyGeochemicalsvypointVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + hddcWyGeochemicalsvypointVO.getRowNum() + "行" + hddcWyGeochemicalsvypointVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {
            e.printStackTrace();
            e.getMessage();
            return "导入失败，请检查数据正确性";
        }
    }

    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList( List<HddcWyGeochemicalsvypointVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcWyGeochemicalsvypointEntity hddcWyGeochemicalsvypointEntity = new HddcWyGeochemicalsvypointEntity();
            HddcWyGeochemicalsvypointVO hddcWyGeochemicalsvypointVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(hddcWyGeochemicalsvypointVO, hddcWyGeochemicalsvypointEntity);
            saveHddcWyGeochemicalsvypoint(hddcWyGeochemicalsvypointEntity);
        }
    }

    @Override
    public List<HddcWyGeochemicalsvypointEntity> findAllByCreateUserAndIsValid(String userId, String isValid) {
        List<HddcWyGeochemicalsvypointEntity> list = hddcWyGeochemicalsvypointRepository.findAllByCreateUserAndIsValid(userId, isValid);
        return list;
    }


    /**
     * 逻辑删除-根据项目id删除数据
     * @param projectIds
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcWyGeochemicalsvypointEntity> hddcA1InvrgnhasmaterialtableList = this.hddcWyGeochemicalsvypointRepository.queryHddcA1InvrgnhasmaterialtablesByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcA1InvrgnhasmaterialtableList) && hddcA1InvrgnhasmaterialtableList.size() > 0) {
            for(HddcWyGeochemicalsvypointEntity hddcA1Invrgnhasmaterialtable : hddcA1InvrgnhasmaterialtableList) {
                hddcA1Invrgnhasmaterialtable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcA1Invrgnhasmaterialtable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcA1Invrgnhasmaterialtable.setIsValid("0");
                this.hddcWyGeochemicalsvypointRepository.save(hddcA1Invrgnhasmaterialtable);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     * @param taskId
     */
    @Override
    public void deleteByTaskId(List<String> taskId) {
        List<HddcWyGeochemicalsvypointEntity> hddcA1InvrgnhasmaterialtableList = this.hddcWyGeochemicalsvypointRepository.queryHddcA1InvrgnhasmaterialtablesByTaskId(taskId);
        if(!PlatformObjectUtils.isEmpty(hddcA1InvrgnhasmaterialtableList) && hddcA1InvrgnhasmaterialtableList.size() > 0) {
            for(HddcWyGeochemicalsvypointEntity hddcA1Invrgnhasmaterialtable : hddcA1InvrgnhasmaterialtableList) {
                hddcA1Invrgnhasmaterialtable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcA1Invrgnhasmaterialtable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcA1Invrgnhasmaterialtable.setIsValid("0");
                this.hddcWyGeochemicalsvypointRepository.save(hddcA1Invrgnhasmaterialtable);
            }
        }

    }









}
